package com.xyxy.platform.website.common.exception;

import com.alibaba.fastjson.JSON;
import com.xyxy.platform.modules.core.beanvalidator.BeanValidators;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.MediaTypes;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.validation.ConstraintViolationException;
import java.util.Map;


/**
 * 简介: 自定义ExceptionHandler，专门处理Restful异常.
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2015-12-22 09:56
 */
// 会被Spring-MVC自动扫描，但又不属于Controller的annotation。
@ControllerAdvice
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 处理RestException.
     */
    @ExceptionHandler(value = {RestException.class})
    public final ResponseEntity<?> handleException(RestException ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaTypes.JSON_UTF_8));
        return handleExceptionInternal(ex, JSON.toJSONString(ResponseUtils.jsonFail(ex.getMessage(), "接口调用异常!")), headers, ex.status, request);
    }

    /**
     * 处理JSR311 Validation异常.
     */
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public final ResponseEntity<?> handleException(ConstraintViolationException ex, WebRequest request) {
        Map<String, String> errors = BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaTypes.JSON_UTF_8));
        ResponseMessage<?> message = ResponseUtils.jsonFail(errors, "接口调用异常!");
        return handleExceptionInternal(ex, JSON.toJSONString(message), headers, HttpStatus.BAD_REQUEST, request);
    }
}
